import * as echarts from '../components/ec-canvas/echarts';
import {
  parseTime
} from '../../utils/util';
const app = getApp();
var config = require('../../script/config.js');
var http = require('../../script/revenue.js');
Component({
  options: {
    addGlobalClass: true,
  },
  /**
   * 组件的属性列表
   */
  properties: {
    key: {
      type: Number,
      value: 0
    },
  },
  observers: {
    'key': function (val) {
      if (val != null && val > 0) {
        this.GetData();
      }
    }
  },
  lifetimes: {
    created: function () {
      this.GetData();
    },
    attached: function () {},
    ready: function () {
      this.ecComponent_trendCharge = this.selectComponent('#trendCharge-chart-dom');
      this.initTrendChargeChart();
      this.ecComponent_heatstatus = this.selectComponent('#heatstatus-chart-dom');
      this.initHeatStatusChart();
    },
    detached: function () {
      if (this.chart_trendCharge) {
        this.cchart_trendChargehart.dispose();
        this.cchart_trendChargehart = null;
      }
      if (this.chart_heatstatus) {
        this.chart_heatstatus.dispose();
        this.chart_heatstatus = null;
      }
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    /************ 收费概况 ***********/
    SumInfo: {
      TOTAL_HEAT_AREA: 0,
      TOTAL_FACT_AREA: 0,
      TOTAL_RCVBL_AMT: 0,
      TOTAL_OWE_AMT: 0,
      TOTAL_RCVBL_THIS: 0,
      RCVBL_RCVED_RATE: 0,
    },
    /************ 收费概况 ***********/

    /************ 收费趋势分析 ***********/
    ecTrendCharge: {
      lazyLoad: true
    },
    chargeTrendMode: 0,
    ChargeTrend: null,
    noTrendData: false,
    ChargeTrendChartData: [],
    /************ 收费趋势分析 ***********/

    /************ 用热状态分析 ***********/
    ecHeatstatus: {
      lazyLoad: true
    },
    HeatStatusChartData: [],
    HeatStatus: null,
    noStatusData: false,
    /************ 用热状态分析 ***********/

    /************ 收费率排行榜 ***********/
    PayRates: [],
    chargeRankData: [],
    chargeRankMode: 1,
    noRankData: false,
    /************ 收费率排行榜 ***********/
    baseUrl: config.baseUrl,
    color: ['#01e1fb', '#00a8ff', '#3270ff', '#40e1d1', '#ff9900', '#ff6600', '#ff0000'],
  },

  /**
   * 组件的方法列表
   */
  methods: {
    GetData() {
      http.GetRevenueTotalData().then(res => {
        if (res.code === 200) {
          const DebtInfo = res.data.DebtInfo; // 收费概览
          const ChargeTrend = res.data.ChargeChart; // 收费趋势
          const HeatStatus = res.data.HeatStatus; // 用热状态
          const PayRates = res.data.PayRates || []; // 收费率排行
          this.setData({
            SumInfo: {
              TOTAL_HEAT_AREA: DebtInfo ? DebtInfo.TOTAL_HEAT_AREA / 10000: 0,
              TOTAL_FACT_AREA: DebtInfo ? DebtInfo.TOTAL_FACT_AREA / 10000 : 0,
              TOTAL_RCVBL_AMT: DebtInfo ? DebtInfo.TOTAL_RCVBL_AMT / 10000 : 0,
              TOTAL_RCVBL_THIS: DebtInfo ? (DebtInfo.TOTAL_RCVBL_AMT - DebtInfo.TOTAL_OWE_AMT_) / 10000 : 0,
              TOTAL_OWE_AMT: DebtInfo ? DebtInfo.TOTAL_OWE_AMT / 10000 : 0,
              RCVBL_RCVED_RATE: DebtInfo ? DebtInfo.RCVBL_RCVED_RATE : 0,
            },
            ChargeTrend,
            HeatStatus,
            PayRates,
          });
          this.getCharteTrendData();
          this.getHeatStatusData();
          this.getchargeRateRankData();
        }
      })
    },
    calcNum(num) {
      return num / 10000
    },
    changeTrendMode(e) {
      const mode = parseInt(e.currentTarget.dataset.mode);
      if (this.data.chargeTrendMode === mode) return;
      this.setData({
        chargeTrendMode: mode
      });
      this.getCharteTrendData();
    },
    getCharteTrendData() {
      let list = []
      let noData = false;
      if (this.ChargeTrend == null) {
        noData = true;
      } else {
        if (this.data.chargeTrendMode === 0) {
          list = this.ChargeTrend.DaysChart_7.ChargeInfoCount;
        } else if (this.data.chargeTrendMode === 1) {
          list = this.ChargeTrend.MonthChart.ChargeInfoCount;
        }
        noData = list.length === 0;
      }
      this.setData({
        ChargeTrendChartData: list,
        noTrendData: noData
      });
      this.setTrendChartOption();
    },
    getHeatStatusData() {
      const list = [];
      let noData = false;
      if (this.data.HeatStatus == null) {
        noData = true;
      } else {
        let total = 0;
        for (let k in this.data.HeatStatus) {
          const val = this.data.HeatStatus[k] ? this.data.HeatStatus[k] : 0
          list.push({
            name: k,
            value: val
          });
          total += val;
        }
        for (var j = 0; j < list.length; j++) {
          list[j].rate = total === 0 ? 0 : ((list[j].value / total) * 100).toFixed(2);
        }
        if (list.length === 0) {
          noData = true;
        }
      }
      this.setData({
        noStatusData: noData,
        HeatStatusChartData: list
      });
      console.log(list)
      this.setHeatStatusOption();
    },
    changeRankMode(e) {
      const mode = parseInt(e.currentTarget.dataset.mode);
      if (this.data.chargeRankMode === mode) return;
      this.setData({
        chargeRankMode: mode
      });
      this.getchargeRateRankData();
    },
    getchargeRateRankData() {
      const mode = this.data.chargeRankMode;
      const thisData = this.data.PayRates.find(item => item.RateType === mode);
      let rankData = [];
      if (thisData && thisData.Rate && thisData.Rate.length > 0) {
        rankData = thisData.Rate;
      }
      this.setData({
        chargeRankData: rankData,
        noRankData: rankData.length === 0
      });
    },
    initTrendChargeChart: function () {
      this.ecComponent_trendCharge.init((canvas, width, height, dpr) => {
        // 获取组件的 canvas、width、height 后的回调函数
        // 在这里初始化图表
        const chart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr // new
        });
        // setOption(chart);


        // 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
        this.chart_trendCharge = chart;
        this.setTrendChartOption();
        // 注意这里一定要返回 chart 实例，否则会影响事件处理等
        return chart;
      });
    },
    initHeatStatusChart: function () {
      this.ecComponent_heatstatus.init((canvas, width, height, dpr) => {
        // 获取组件的 canvas、width、height 后的回调函数
        // 在这里初始化图表
        const chart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr // new
        });
        this.chart_heatstatus = chart;
        this.setHeatStatusOption();
        // 注意这里一定要返回 chart 实例，否则会影响事件处理等
        return chart;
      });
    },
    setTrendChartOption() {
      if (!this.chart_trendCharge) return;
      if (this.data.ChargeTrendChartData.length === 0) return;
      let yData = [];
      let xData = [];
      const resData = [...this.data.ChargeTrendChartData];
      for (let i = 0; i < resData.length; i++) {
        xData.push(resData[i].payDate.slice(5));
        yData.push(resData[i].payMoney);
      }
      const option = {
        tooltip: {
          trigger: 'axis',
          textStyle: {
            textShadowBlur: 0,
          },
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          },
          // renderMode: 'richText',
          valueFormatter: function (val) {
            return val + " 万元";
          },
        },
        legend: {

        },
        grid: {
          top: '50',
          right: '10',
          left: '20',
          bottom: '30',
          containLabel: true,
        },
        xAxis: [{
          type: 'category',
          boundaryGap: false,
          axisTick: {
            alignWithLabel: true
          },
          axisLabel: {
            formatter: (val) => {
              return val.slice(5, 10)
            }
          },
          data: xData,
          axisPointer: {
            type: 'shadow'
          }
        }],
        yAxis: [{
          type: 'value',
          name: '金额（万元）',
          axisLine: {
            show: true,
          },
          axisLabel: {

          }
        }],
        series: [{
          name: '收费金额',
          type: 'line',
          data: yData,
          smooth: true,
          // showSymbol: false,
          itemStyle: {
            color: 'rgba(233,70,27,1)',
            shadowColor: 'rgba(0, 0, 0, 0.5)',
            shadowBlur: 10
          },
          areaStyle: {
            opacity: 0.6,
            color: 'rgba(233,70,27,.5)'
          },
          emphasis: {
            focus: 'series'
          },
        }]
      };
      this.chart_trendCharge.setOption(option);
    },
    setHeatStatusOption() {
      if (!this.chart_heatstatus) return;
      if (this.data.HeatStatusChartData.length === 0) return;
      const option = {
        grid: {
          top: "0",
          left: "10",
          right: "10",
          bottom: "10",
          containLabel: true,
        },
        color: this.data.color,
        title: {
          text: "用热状态",
          top: "middle",
          left: "center",
          textStyle: {
            color: "#606266",
            fontSize: 13,
            fontWeight: "bold",
          },
        },
        tooltip: {
          trigger: 'item',
          valueFormatter: function (val) {
            return val + " 户";
          },
          textStyle: {
            color: "#313131",
            fontSize: 13,
          },
          confine: true,
        },
        legend: {
          show: false,
          orient: "vertical",
          right: "20",
          top: "middle",
          itemWidth: 20,
          itemHeight: 15,
          textStyle: {
            color: "#606266",
            fontSize: 13,
          },
        },
        toolbox: {
          show: false,
        },
        series: {
          name: "用热状态",
          type: "pie",
          clockWise: false,
          radius: ["45%", "70%"],
          center: ["50%", "50%"],
          hoverAnimation: false,
          avoidLabelOverlap: false,
          padAngle: 3,
          label: {
            show: false,
            formatter: "{b|{b}}\n{d|{d}%}",
            rich: {
              b: {
                fontSize: 12,
                color: "#606266",
                align: "left",
                width: "100%",
              },
              d: {
                fontSize: 14,
                color: "#606266",
                align: "left",
              },
            },
          },
          itemStyle: {
            borderRadius: 6,
          },
          data: this.data.HeatStatusChartData,
        },
      };
      this.chart_heatstatus.setOption(option);
    },
    getLastSevenDays() {
      const today = new Date();
      const dates = [];
      for (let i = 6; i >= 0; i--) {
        const date = new Date(today);
        date.setDate(today.getDate() - i);
        dates.push(parseTime(date, 'yyyy-MM-dd'));
      }
      return dates;
    },
    getDatesOfThisMonth() {
      const dates = [];
      const today = new Date();
      const year = today.getFullYear();
      const month = today.getMonth();
      const todayDate = today.getDate(); // 获取今天是几号

      for (let i = 1; i <= todayDate; i++) {
        const date = new Date(year, month, i);
        dates.push(parseTime(date, 'yyyy-MM-dd'));
      }

      return dates;
    }
  }
})